import random
import logging

from django.shortcuts import render
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from django_redis import get_redis_connection
from django.views import View
from django.http import HttpResponse, JsonResponse

logger = logging.getLogger('django')


# Create your views here.

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一表示图形验证码所属于的用户
        :return: image/jpeg
        """
        # 生成图形验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, 300, text)

        return HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    """短信验证码"""

    def get(self, request, mobile):
        """

        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        # 接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 校验参数
        if not all([image_code_client, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('code')
        # 提取图形验证码
        image_code_server = redis_conn.get('ima_%s' % uuid)
        if image_code_server is None:
            # 图形验证码过期或不存在
            return JsonResponse({'code': 400, 'errmsg': '图形验证码失效'})

        # 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        # 对比图形验证码
        image_code_server = image_code_server.decode()  # bytes转字符串
        if image_code_client.lower() != image_code_server.lower():  # 转小写后比较
            return JsonResponse({'code': 400, 'errmsg': '输入的图形验证码有误'})

        # 生成短信验证码，生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'code': 400, 'errmsg': '发送短信过于频繁'})
        pl = redis_conn.pipeline()
        # 保存短信验证码
        pl.setex('sms_%s' % mobile, 300, sms_code)
        # 写入send_flag
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()
        # 发送短信验证码
        CCP().send_template_sms(mobile, [sms_code, 5], 1)

        # 响应结果
        return JsonResponse({'code': 0, 'errmsg': '发送短信成功'})
